package com.david.func_test.activity

import android.animation.ValueAnimator
import android.animation.ValueAnimator.INFINITE
import android.animation.ValueAnimator.REVERSE
import android.app.Activity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.core.view.updateLayoutParams
import com.airbnb.lottie.LottieAnimationView
import com.david.func_test.widget.AnimItemBean
import com.david.func_test.widget.BubbleItemsWidget
import com.david.func_test.R

class LottieAnimTestActivity: Activity() {
    private lateinit var itemsWidget: BubbleItemsWidget
    lateinit var lottieAnimationView: LottieAnimationView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lottie_anim_test)

        lottieAnimationView = findViewById<LottieAnimationView>(R.id.lottie_view)
        lottieAnimationView.let {
            it.setAnimationFromUrl("https://www.baidu.com/native-cache/data.json")
            it.playAnimation()
        }
        lottieAnimationView.post {
            itemsWidget = BubbleItemsWidget(findViewById(R.id.bubble_parent), lottieAnimationView.width/6,
                (lottieAnimationView.left + (lottieAnimationView.right - lottieAnimationView.left)/2),
                (lottieAnimationView.top + (lottieAnimationView.bottom - lottieAnimationView.top)/2),
                lottieAnimationView.width / 2 + lottieAnimationView.width/6
            )
            itemsWidget.setItems(arrayListOf(AnimItemBean("test"), AnimItemBean("test"), AnimItemBean("test"), AnimItemBean("test"), AnimItemBean("test")))
        }

//        startAnim(findViewById(R.id.anim_item))
    }

    private fun startAnim(view: View){
        val valueAnimator = ValueAnimator.ofInt(0, 30)
        valueAnimator.duration = 1000
        valueAnimator.repeatCount = INFINITE
        valueAnimator.repeatMode = REVERSE
        valueAnimator.addUpdateListener { animator -> // 获得每次变化后的属性值
            val currentValue = animator.animatedValue as Int

            view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
                topMargin = 50 + currentValue
            }
//            (view.layoutParams as FrameLayout.LayoutParams).topMargin = 50 + currentValue
//            view.requestLayout()
        }
        valueAnimator.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        lottieAnimationView.cancelAnimation()
        itemsWidget.onDestroy()
    }
}